<?php
/**
 * Created by PhpStorm.
 * User: zhangyi
 * Date: 17/3/5
 * Time: 下午11:05
 */
use yii\helpers\Url;
use yii\widgets\LinkPager;
use dosamigos\datepicker\DateRangePicker;
use backend\components\ReverseLinkPager;
use yii\bootstrap\Modal;

conquer\gii\GiiAsset::register($this);

?>

<div id="page-wrapper" style="min-height: 362px;">
    <div class="row" style="margin: 10px 0;">
        <div class="col-lg-12">
            <form class="form-inline">
                <div class="input-append">
                    <input type="text" name="MemberSearch[username]" value="<?= $searchModel->username ?>" placeholder="请输入用户名关键词" class="form-control">
                    <?= DateRangePicker::widget([
                        'language'=>'zh-CN',
                        'name' => 'MemberSearch[start]',
                        'value' => $searchModel->start,
                        'nameTo' => 'MemberSearch[end]',
                        'valueTo' => $searchModel->end,
                        'options' => array(
                            'placeholder'=>'注册时间',
                        ),
                        'optionsTo' => array(
                            'placeholder'=>'注册时间',
                        ),
                        'clientOptions'=>[
                            'autoclose'=>true,
                            'format'=>"yyyy-mm-dd",
                            'clearBtn'=>true
                        ],
                    ]);?>
                    <input type="text" name="MemberSearch[mobile]" value="<?= $searchModel->mobile ?>" placeholder="请输入电话号码" class="form-control">
                    <input type="text" name="MemberSearch[channel]" value="<?= $searchModel->channel ?>" placeholder="请输入渠道关键词" class="form-control">

                    <input type="text" name="MemberSearch[zhuangtai]" value="<?= $searchModel->zhuangtai ?>" placeholder="请输入状态关键词" class="form-control">
                    <input type="text" name="MemberSearch[note]" value="<?= $searchModel->note ?>" placeholder="请输入备注关键词" class="form-control">

                    <button type="submit" class="btn">搜索</button>

                    <a href="<?= Url::to(['manage/export']+$gets) ?>" class="btn btn-primary">导出</a>
                </div>
            </form>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-12">
            <table class="table table-striped table-bordered table-hover dataTable no-footer" id="dataTables-example" role="grid" aria-describedby="dataTables-example_info">
                <thead>
                <tr role="row">
                    <th style=""></th>
                    <th style="">序号</th>
<!--                    <th style="">ID</th>-->
                    <th style="">用户名</th>
                    <th style="">电话</th>
                    <th style="">渠道来源</th>
                    <th style="">注册时间</th>
                    <th style="">状态</th>
                    <th style="">备注</th>
                    <th style="">操作</th>
                </thead>
                <tbody>
                <?php
                $roles = Yii::$app->authManager->getRolesByUser(Yii::$app->user->id);
                $role = array_shift($roles);

                $serials = $pages->limit+$pages->offset;
                if($serials >= $pages->totalCount) {
                    $serials = $pages->totalCount;
                }
                $trs = '';
                foreach($models as $model) {
                    $time = date('Y-m-d H:i:s',$model->create_time);
                    $editurl = Url::to(['manage/userinfo','id'=>$model->id]);
                    $pushurl = Url::to(['manage/pushmessage','id'=>$model->id]);
                    $mobile = $model->mobile;
                    if($role->name=='查看会员渠道组') {
                        $mobile = '******';
                    }

                    $trs.=<<<TR
                <tr class="gradeA odd" role="row" data-id="{$model->id}">
                    <td class="center"><input type="checkbox" class="member-id" value="{$model->id}"></td>

                    <td class="center">{$serials}</td>
                    <td class="center">{$model->username}</td>
                    <td class="center">{$mobile}</td>
                    <td class="center">{$model->channel}</td>
                    <td class="center">{$time}</td>
                    <td class="center zhuangtai" data-id="{$model->id}" data-type="zhuangtai">{$model->zhuangtai}</td>
                    <td class="center note" data-id="{$model->id}" data-type="note">{$model->note}</td>
                    <td class="center"><a href="javascript:;" onclick="del({$model->id})">删除</a> |  <a href="{$editurl}">详情</a>
                      |  <a class="show-modal" data-target="#modal_view" data-header="APP推送" href="{$pushurl}">推送</a>
                    </td>
                </tr>
TR;
                    $serials--;

                }
                echo $trs;
                ?>

                </tbody>
            </table>
            <div class="row">
                <div class="col-sm-12">
                    <label><input type="checkbox" class="allselect"> 全选本页</label>
                    <label><input type="checkbox" class="all-eligibility-member"> 所有满足条件用户</label>
                    <a class="batch-push" data-target="#modal_view" data-header="APP推送" href="/manage/pushmessage?id=0">批量推送</a>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-12">
                    <div class="dataTables_paginate paging_simple_numbers">
                        <?php
                        echo ReverseLinkPager::widget([
                            'pagination' => $pages,
                            'maxButtonCount'=>5,
                            'firstPageLabel'=>'首页',
                            'lastPageLabel'=>'最后一页',
                        ]);
                        ?>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>

<script>
    function del(n){
        if(confirm('确定删除此？')){
            $.post('<?= Url::to(['manage/deluser']) ?>',{id:n,'<?= Yii::$app->request->csrfParam ?>':'<?= Yii::$app->request->getCsrfToken() ?>'},function(v){
                if(v.f){
                    alert('删除成功！');
                    location.reload();
                }else{
                    alert(v.data);
                }
            },'json');
        }
    }
    function ck(n){
        $('.form-inline').submit();
    }

</script>
<style>
    .input-daterange{
        width: 100%;
        vertical-align: middle
    }

    @media (min-width: 768px) {

        .input-daterange {
            display: inline-block;
            width: 300px;
            vertical-align: middle
        }
    }
</style>
<?php
$modifyUrl = Url::to(['manage/edit-memberinfo']);
$csrfparam = json_encode(array(Yii::$app->request->csrfParam=>Yii::$app->request->getCsrfToken()));
$condition = json_encode(Yii::$app->request->queryParams);

$js=<<<JS

    $('.zhuangtai,.note').dblclick(function(){
            var content = $(this).html();
            var datas = $(this).data();

            if($(this).find("textarea").length>0) return false;

            var textarea = '<textarea row=6>'+content+'</textarea>';
            $(this).html(textarea);
            $(this).find('textarea').focus();
    });
    $(document).on('click','#dataTables-example',function(e){
        var target = e.target.nodeName;

        if(target.toUpperCase() == 'TEXTAREA') {
            return false;
        }
        $('#dataTables-example textarea').each(function(){
            var csrfparam = {$csrfparam};
            var td = $(this).closest('td');
            var datas = td.data();
            datas['content'] = $(this).val();

            $.extend(datas,csrfparam);
            $.ajax({
                type:'POST',
                url:"{$modifyUrl}",
                data:datas,
                dataType:'json',
                success:function(result) {
                    if(result['error']!='ok') {
                        alert(result['errorinfo']);
                    } else {
                        td.html(result['content']);
                    }
                },
            });
        });
    });

   $(document).ajaxComplete(function (event, xhr, settings) {
        if(!xhr.responseJSON) return false;
        $('#modal_view').modal('hide')

        if(xhr.responseJSON.pushstate.success=='ok') {

                alert('推送成功');
        } else if(xhr.responseJSON.pushstate.success=='fail') {

                alert('推送失败');
        }

   });
   $('.allselect').on('click',function(){
        if($(this).is(':checked')) {

                $('.member-id').each(function(){
                    $(this).prop('checked',true);
                });
                $('.all-eligibility-member').prop('checked',false);

        } else {
                $('.member-id').each(function(){
                    $(this).prop('checked',false);
                });

        }
   });

   $('.all-eligibility-member').on('click',function(){
        if($(this).is(':checked')) {

                $('.allselect').prop('checked',false);
                $('.member-id').each(function(){
                    $(this).prop('checked',false);
                });

        }
   });

   $(document).on('click', '.batch-push',  function(){
        var self = $(this),
        	target = $(self.attr('data-target')),
            ajax_url = self.attr('data-url') || self.attr('href'),
            header = self.attr('data-header')||'';
		var h4 = target.find('.modal-header').find('h4');
		if (h4.length === 0) {
		    $('<h4>'+header+'</h4>').appendTo(target.find('.modal-header'));
		} else {
			h4.text(header);
		}
		var ids=[];
		if($('.allselect').is(':checked')) {
			$('.member-id').each(function(){
		       if($(this).is(':checked')) {
		            //console.info($(this).val());
		            ids.push($(this).val());
		       }
		    });
		} else {
			ids.push('all');
		}
        var condition;
        if($('.all-eligibility-member').is(':checked')) {
        		 condition = {$condition};
        }
        //console.info(condition);
		var csrfparam = {$csrfparam};
		var datas = {ids:ids,condition:condition};

		$.extend(datas,csrfparam);
		//console.info(datas);

        if (ajax_url) {
        	var body = target.modal('show').find('.modal-body').empty();
        	$.ajax({
    			url: ajax_url,
    			type:'POST',
    			data:datas,
    			success: function (response) {
    				body.html(response);
    			},
    			error: function (jqXHR) {
    				body.html('<div class="error-summary">'+jqXHR.responseText+'</div>');
    			}
    		});
        	return false;
        }
    });
JS;
$this->registerJs($js);
?>

<?= Modal::widget([
    'id' => 'modal_view',
    'clientEvents' => [
        'hidden.bs.modal'=>'function (e) {
                $(this).find(".modal-body").html("");
            }',
    ],
]); ?>


